
package org.openeai.lite.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;

import org.apache.log4j.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.openeai.lite.common.exception.OpenEAIException;


public class FileUtils
{

    private static Logger log = Logger.getLogger(FileUtils.class);

    public URI fileNameToURI(String fileName)
    {
        File file = new File(fileName);
        URI uri = file.toURI();

        return uri;
    }

    public void copyToUploadedCustomConfig(UploadedFile uploadedConfigFile)
                    throws OpenEAIException
    {

        log.info("Creating/overwriting temporary file " + Constants.CUSTOM_CONFIG_FILENAME
                        + " with content from file " + uploadedConfigFile.getName());

        try
        {

            File customConfigFile = new File(Constants.CUSTOM_CONFIG_FILENAME);
            if (!customConfigFile.exists())
            {
                File dir = customConfigFile.getParentFile();
                dir.mkdirs();
            }
            byte[] data = new byte[(int) uploadedConfigFile.getSize()];
            InputStream is = uploadedConfigFile.getInputStream();
            is.read(data);
            is.close();
            FileOutputStream fos = new FileOutputStream(customConfigFile);
            fos.write(data);
            fos.close();
            log.info("Temporary file created.");
        }
        catch (Exception e)
        {
            log.error("Error writing to temporary file " + Constants.CUSTOM_CONFIG_FILENAME, e);
            throw new OpenEAIException("Error writing to temporary file "
                            + Constants.CUSTOM_CONFIG_FILENAME, e);
        }
    }

}
